#include <FL/Fl.H>
#include <FL/Fl_Gl_Window.H>
#include <FL/gl.h>
#include <math.h>
#include <vector> 
#include <cassert>
#include <fstream>
#include <iostream>


 
void write_mat(const char* fpath, std::vector<  float  > y) { 
  std::ofstream fout(fpath, std::ios::out | std::ios::binary);
  assert(fout);
  int len = y.size();
 
  fout.write( (char*)&len, sizeof(int));
  fout.write( (char*)&y[0], sizeof(float)*len);
  fout.close();
}


class myGL : public Fl_Gl_Window { 
  std::vector<float> v;

  void draw() {
    if (!valid()) {
      valid(1);
      glMatrixMode (GL_PROJECTION);
      glLoadIdentity ();
      glOrtho (0, w(), h(), 0, 0, 1);
      glMatrixMode (GL_MODELVIEW);
      glDisable(GL_DEPTH_TEST);
    }
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE);
    glVertex2f(0, h()/2);
    glVertex2f(w(), h()/2);
    glEnd();

    glColor3f(1.0, .5, 1.0);
    glBegin(GL_LINES);
    for ( unsigned i=0; i<v.size(); i++ ) {
      glVertex2f( ((float)i/v.size()) * w() , v[i] );
      //std::cout << "drawing vertex = (" <<  ((float)i/v.size())*(float)w() <<","<< v[i] <<")\n";
    }
    glEnd();
  }
  
  int handle( int event ) {
    switch ( event ) {
    case FL_DRAG:
      printf("dragging!\n");
    case FL_PUSH:
      if( Fl::event_button() == 1 ) {
	printf("Left mouse button pressed.\n");
	printf("width: %d\n", w());
	//v.push_back( (float)Fl::event_y () );
	
	float mx  = (float)Fl::event_x();
	float idx =  mx / w() * v.size();
	float pdx =  (mx - 1) / w() * v.size();
	float ndx =  (mx + 1) / w() * v.size();

	printf("p: %f, i: %f, n: %f\n", idx);


	if( floor(idx) < 0 || floor(idx) > v.size() ) { return 1; }

	v[floor(idx)] =   floor((float)Fl::event_y());
	
	redraw();
	return 1;
      }
    default:
      // letting the base class handle events I don't care
      // about, or don't dare mess with.
      return Fl_Gl_Window::handle(event);
    }
  }

public:
  myGL(int X,int Y,int W,int H,const char*L=0) : Fl_Gl_Window(X,Y,W,H,L) {
    end();
    v.resize(41000,10);
  }
};



int main(void) {
  // this creates our window
  Fl_Window win(500, 500);
  myGL gWin(10, 10, win.w()-20, win.h()-20);
  //not sure how/why this works
  win.resizable(&gWin);
  //makes the window show up
  win.show();
  // This causes the fltk stuff to run until the window's closed
  return(Fl::run());
}
